package com.ssyc.main.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.ssyc.common.appupdate.AppBean;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 启动页面
 * Created by Administrator on 2018/1/11 0011.
 */

public class WelcomeActivity extends AppCompatActivity {

    private String account;

    private String role;

    private String pettype;

    private Handler handler = new Handler();

    //默认组件
    private ComponentName componentNameDefault;

    //春节组件
    private ComponentName yearComponent;

    //春节的Icon标识
    String yearPath = "com.ssyc.jpxb.year";

    //默认的Icon标识
    String defPath = "com.ssyc.jpxb.def";

    public static final String APKVERSONURL = "https://www.moregolden.com:8018/ycsj_platform_nce2/AppVerMsg";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //先判断版本4.2以下不让进入APP
        judgeVersion();

    }

    //判断用户版本4.2以下直接退出APP
    private void judgeVersion() {
        int sdkVersion = android.os.Build.VERSION.SDK_INT;
        if (sdkVersion <= 21) {
            //小于4.2以下
            ToastUtils.showShort("当前版本过低,不能使用APP");
            finish();

        } else {

            //初始化账号
            initData();

            //请求Icon接口
//        http();

            IntentActivity();

        }

    }



    private void IntentActivity() {
        //延迟跳转
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                goActivity();
            }
        }, 1000);
    }



    private void http() {

        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        params.put("app", "android");
        params.put("page", "0");
        params.put("platform", "8");


        OkHttpUtils.post().url(APKVERSONURL).params(params).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                IntentActivity();
            }

            @Override
            public void onResponse(String response, int id) {

                //服务器返回的版本数据json
                AppBean appBean = null;

                try {
                    appBean = GsonUtil.jsonToBean(response, AppBean.class);
                    //获取动态图标
                    if (!TextUtils.isEmpty(appBean.getServerjson().getApp_icon())) {
//                        SPUtil.put(WelcomeActivity.this, SpKeys.YEARICON, appBean.getServerjson().getApp_icon());

                        //实现APP的动态替换图标,初始化组件
//                        initCompent();

                        //切换组件更改Icon
//                        changeIconMethod(appBean.getServerjson().getApp_icon());

//                        IntentActivity();
                    }

                } catch (Exception e) {
                    Log.i("test", "解析版更新数据错误");
                    IntentActivity();
                }
            }
        });
    }


    /**
     * 初始化组件的方法
     */
    private void initCompent() {
        yearComponent = new ComponentName(getApplication(), yearPath);
        componentNameDefault = new ComponentName(getApplication(), defPath);
    }


    /**
     * 启用组件
     *
     * @param componentName 重要方法
     */
    private void enableComponent(Activity activity, ComponentName componentName) {
        PackageManager pm = activity.getPackageManager();
        int state = pm.getComponentEnabledSetting(componentName);
        if (PackageManager.COMPONENT_ENABLED_STATE_ENABLED == state) {
            //已经启用
            return;
        }
        pm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }


    /**
     * 禁用组件
     *
     * @param componentName 重要方法
     */
    private void disableComponent(Activity activity, ComponentName componentName) {
        PackageManager pm = activity.getPackageManager();
        int state = pm.getComponentEnabledSetting(componentName);
        if (PackageManager.COMPONENT_ENABLED_STATE_DISABLED == state) {
            //已经禁用
            return;

        }
        pm.setComponentEnabledSetting(componentName,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    /**
     * 根绝服务器返回的标识动态切换Icon的方法
     */
    private void changeIconMethod(String yearIcon) {

        //Icon是否变化
        if (!yearIcon.equals(SPUtil.getString(this, SpKeys.LASTICON))) {

            if (TextUtils.isEmpty(yearIcon) || "0".equals(yearIcon)) {
                //默认Icon
                disableComponent(this, yearComponent);
                enableComponent(this, componentNameDefault);
            } else if ("1".equals(yearIcon)) {
                //春节Icon
                disableComponent(this, componentNameDefault);
                enableComponent(this, yearComponent);
            }

            SPUtil.put(this, SpKeys.LASTICON, yearIcon);

            IntentActivity();
        } else {
            IntentActivity();
        }
    }


    /**
     * 初始化账号系统
     */
    private void initData() {
        account = AccountUtils.getAccount(getBaseContext());
        role = AccountUtils.getRole(getBaseContext());
        pettype = SPUtil.getString(this, SpKeys.SERVICEPETTYPE);
    }

    /**
     * 动画结束后判断是否第一次进入
     * true:跳转到Glide界面
     * false:根据角色跳转到不同角色的对应的逻辑界面
     */
    private void goActivity() {

        if (!SPUtil.getBoolean(this, SpKeys.ISFIRST)) {
            //是第一次登陆
            UiUtils.startActivity(this, GuideActivity.class);
            SPUtil.put(this, SpKeys.ISFIRST, true);
        } else {
            //是否登录
            if (!TextUtils.isEmpty(account)) {
                //学生身份
                if ("0".equals(role)) {
                    //是否领取宠物
                    if (!TextUtils.isEmpty(pettype)) {
                        //首页
                        ARouter.getInstance().build("/student/StudentMainActivity").navigation();
                    } else {
                        //领取宠物
                        ARouter.getInstance().build("/student/studentgetpetone").navigation();
                    }
                } else if ("1".equals(role)) {
                    //家长
                    ARouter.getInstance().build("/parents/ParentsMainActivity").navigation();
                } else if ("2".equals(role)) {
                    // 老师
                    ARouter.getInstance().build("/teacher/TeacherMainActivity").navigation();
                } else if ("3".equals(role)) {
                    //校长
                    ARouter.getInstance().build("/master/MasterMainActivity").navigation();
                }
            } else {
                //未登录
                UiUtils.startActivity(this, ChooseRoleActivity.class);
            }
        }

        this.finish();
    }

    @Override
    protected void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }
}
